package controller;

import com.alibaba.dubbo.config.annotation.Reference;
import entity.ResponseResult;
import entity.Users;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.UserService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: lagou-dubbo
 * @Author: GuoAn.Sun
 * @CreateTime: 2020-07-27 18:16
 * @Description: 控制层
 */
@Controller
public class UserAction {

    @Reference
    private UserService userService;

    @RequestMapping("/getUserList")
    @ResponseBody
    public List<Users> getUserList(String username){
        Users users = new Users();
        users.setUsername(username);
        List<Users> usersList = userService.getUserList(users);
        System.out.println(usersList);
//        return new ModelAndView("index.jsp", "users", usersList);
        return usersList;
    }

    @PostMapping("/register")
    @ResponseBody
    public ResponseResult register(@RequestBody Users user) {
        System.out.println("来注册");
        try {
            String nowTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            user.setCreatetime(nowTime);
            userService.register(user);
            return  new ResponseResult(true,200,"注册成功",null);
//            return "注册成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return  new ResponseResult(false,201,"注册失败",null);
//            return "失败";
        }
    }

    @PostMapping("/userUpdate")
    @ResponseBody
    public ResponseResult userUpdate(@RequestBody Users user){
        try {
            userService.userUpdate(user);
            return  new ResponseResult(true,200,"修改成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return  new ResponseResult(false,201,"修改失败",null);
        }
    }

    @RequestMapping("/deleteUserByUid")
    @ResponseBody
    public ResponseResult deleteUserByUid(int uid) {
        try{
            userService.deleteUserByUid(uid);
            return new ResponseResult(true, 200, "删除成功！", null);
        }
        catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(false, 201, "删除失败！", null);
        }
    }
}
